(function() {
    'use strict';

    /**
     * @ngdoc directive
     * @name webApp.directive:catTree
     * @description

     用法：
     <cat-tree ng-model="item.cid" dft="1"></cat-tree>
     注：必须绑定ng-model;dft=1代表自动选中最后一个节点

     * # catTree
     */
    angular.module('webApp')
        .directive('catTree', function() {
            return {
                restrict: 'E',
                template: '<ul id="{{id}}" class="ztree" ></ul>',
                replace: true,
                require: 'ngModel',
                scope: {
                    ngModel: '=',
                    dft: '@', //是否初始化到一个节点
                    obj: '@', //是否返回obj对象，不设置返回类目数字id，否则返回类目节点对象{id:123,name:"aaa"}
                    ty: '@',
                    add: '@',
                    // store: "=",
                    apitype: "@",
                    checkbox: "@",
                },
                controller: ['$scope', 'dataService', '$compile', '$timeout', '$rootScope', function($scope, dataService, $compile, $timeout, $rootScope) {
                    var zTreeObj;
                    $scope.chosedId = null;
                    // zTree 的参数配置，深入使用请参考 API 文档（setting 配置详解）
                    var setting = {
                        check: {
                            enable: true,
                        },
                        callback: {

                        },
                        data: {
                            simpleData: {
                                enable: true
                            }
                        }
                    };
                    $scope.$on('event:up-store-id', function() {
                        $scope.initData();
                    });
                    //选择节点
                    $scope.checkOne = function() {
                        if (zTreeObj && $scope.chosedId) {
                            var nodes = zTreeObj.getNodesByParam("id", $scope.chosedId);
                            if (nodes && nodes.length == 1) {
                                zTreeObj.checkNode(nodes[0], true, true, false);
                            }
                        }
                        if (!$scope.chosedId) {
                            $scope.checkMultiple();
                        }
                    }

                    //选择节点
                    $scope.checkMultiple = function() {
                        if (zTreeObj) {
                            _.map($scope.ngModel, function(da, key) {
                                var nodes = zTreeObj.getNodesByParam("id", da.id);
                                if (nodes && nodes.length == 1) {
                                    zTreeObj.checkNode(nodes[0], true, true, false);
                                }
                            });
                        }
                    }

                    function setNgModel(treeNode) {
                        $timeout(function() {
                            if ($scope.obj) {
                                console.error("da",$scope.treeNode);
                                $scope.ngModel = treeNode.checked ? { id: treeNode.id, name: treeNode.name, cid: treeNode.id,sort: treeNode.sort } : {};
                            } else {
                                $scope.ngModel = treeNode.checked ? treeNode.id : "";
                            }
                        });
                    }

                    function chSetNgModel(treeNode) {
                        $timeout(function() {
                            //获取选中的节点数据
                            var checkary = zTreeObj.getCheckedNodes(true);
                            var ary = [];

                            _.map(checkary, function(da, ke) {
                                console.error("da",da);
                                ary.push({
                                    id: da.id,
                                    name: da.name,
                                    cid: da.id,
                                    sort: da.sort,
                                });
                            });

                            $scope.ngModel = ary;
                        });
                    }

                    function upSetting() {
                        $scope.type = $scope.checkbox ? "checkbox" : "radio";
                        //多选
                        if ($scope.checkbox) {
                            setting.callback.onCheck = function(event, treeId, treeNode) {
                                chSetNgModel(treeNode);
                            };
                        } else {
                            //单选
                            setting.check.chkStyle = "radio";
                            setting.check.radioType = "all";
                            setting.callback.onClick = function(event, treeId, treeNode, clickFlag) {
                                zTreeObj.checkNode(treeNode, true, true, true);
                            };
                            setting.callback.onCheck = function(event, treeId, treeNode) {
                                setNgModel(treeNode);
                            };
                        }
                    }
                    // zTree 的数据属性，深入使用请参考 API 文档（zTreeNode 节点数据详解）
                    $scope.initData = function() {
                        $scope.id = "catTreeWin" + random(11111, 99999);
                        upSetting();
                        //判断是不是商品属性列表
                        if (!$scope.ty) {
                            var query = {};
                            $scope.store = $rootScope.store_id;
                            if ($scope.store) {
                                query.query = { store_id: $scope.store };
                                query.page_size = 100;
                            }
                            var api = "categoryGet";
                            if ($scope.apitype) {
                                api = $scope.apitype;
                            }

                            dataService[api](query,0).then(function(list) {
                                var zNodes = [];
                                if (list.itemcats) {
                                    var listdata = list.itemcats;
                                    for (var i in listdata) {
                                        if (listdata[i].parent_cid !== 0) zNodes.push({ id: listdata[i].cid, pId: listdata[i].parent_cid, name: listdata[i].name, sort: listdata[i].sort, checked: false, open: true });
                                    }
                                }
                                if (list.res_types) {
                                    var listdata = list.res_types;
                                    for (var i in listdata) {
                                        zNodes.push({ id: listdata[i].res_type_id, pId: listdata[i].parent_id, name: listdata[i].name, sort: listdata[i].sort, checked: false, open: true });
                                    }
                                }
                                zTreeObj = $.fn.zTree.init($("#" + $scope.id), setting, zNodes);
                                //选中节点
                                $scope.checkOne();

                            });

                        }
                    }
                    $scope.initData();

                }],

                link: function(scope, elem, attrs, ctrl) {
                    // console.error("ctrl",ctrl,attrs,scope);
                    scope.$watch('ngModel', function(newValue, oldValue, scope) {
                        if (newValue) {

                            if (newValue.id) {
                                scope.chosedId = newValue.id;
                                scope.checkOne();
                            }
                            if (_.isNumber(newValue)) {
                                scope.chosedId = newValue;
                                scope.checkOne();
                            }
                            if (!newValue.id) {
                                scope.initData(); //初始化
                            }
                            if (!newValue.id && newValue.length >= 1) {
                                scope.checkMultiple(newValue);
                            }
                        }
                    });
                    scope.$watch('store', function(newValue, oldValue, scope) {
                        //                         console.log("store-newValue",newValue);
                        if (newValue) {
                            scope.initData(); //初始化
                        }
                    });
                    scope.$watch('checkbox', function(newValue, oldValue, scope) {
                        if (newValue) {
                            scope.initData(); //初始化
                        }
                    });

                    // //处理数据，得到想要 的数据
                    // ctrl.$render = function() {
                    //     //                         console.log("11111", ctrl.$viewValue);
                    //     if (ctrl.$viewValue) {
                    //         if (ctrl.$viewValue.id) {
                    //             scope.chosedId = ctrl.$viewValue.id;
                    //         }
                    //         if (_.isNumber(ctrl.$viewValue)) {
                    //             scope.chosedId = ctrl.$viewValue;
                    //         }

                    //         scope.checkOne();
                    //     }
                    // };
                }
            }
        })
        .directive('displaycat', function() {
            return {
                restrict: 'E',
                template: "<span>{{name}}</span> ",
                replace: true,
                // require: 'ngModel',
                scope: {
                    cid: '=',
                },
                controller: ['$scope', 'dataService', '$compile', '$timeout', '$rootScope', function($scope, dataService, $compile, $timeout, $rootScope) {

                    $scope.init = function() {
                        if ($scope.cid) {
                            var query = { query: { cid: $scope.cid } }
                            dataService.categoryGet(query).then(function(list) {
                                if (list) {
                                    var listdata = list.itemcats[0];
                                     if(listdata){
                                       $scope.name = listdata.name;          
                                    }
                                }
                            });
                        }

                    }

                    $scope.init();

                }],

                link: function(scope, elem, attrs, ctrl) {



                }
            }
        })
        .directive('choiceCat', function() {
            return {
                restrict: 'E',
                template: "<a href='javascript:void(0);' class=''  ng-click='addItem();'><displaycat cid='ngModel' ng-if='ngModel'></displaycat> <span ng-if='!ngModel' >选择类目</span></a> ",
                replace: true,
                require: 'ngModel',
                scope: {
                    ngModel: '=',
                    back: '&',
                },
                controller: ['$scope', 'dataService', '$compile', '$timeout', '$rootScope', function($scope, dataService, $compile, $timeout, $rootScope) {

                    $scope.addItem = function() {
                        showPop();
                    }
                    // console.error("$scope.storeid", $scope.storeid);
                    $scope.$on('event:up-tore-id', function() {
                        showPop();
                    });

                    function showPop() {
                        $scope.storeid = $rootScope.store_id;
                        $scope.ngModel = $scope.ngModel?$scope.ngModel:0;
                        $.alert({
                            backdrop: 'static',
                            keyboard: true,
                            title: '{{"类目" | translate}}',
                            body: '<span> <cat-tree ng-model="ngModel" store="storeid"></cat-tree></span>',
                            okBtn: '{{"ok" | translate}}',
                            closeBtn: true,
                            transition: true,
                            width: 'small',
                            height: 200,
                            show: function(e) {
                                $compile($(e.currentTarget).contents())($scope);
                                return true;
                            },
                            okHide: function(e) {
                                $timeout(function() {
                                    // $scope.ngModel
                                    console.error("$scope.ngModel", $scope.ngModel);
                                    $scope.back({
                                        catid: $scope.ngModel
                                    });
                                });
                            },
                        });
                    }
                }],

                link: function(scope, elem, attrs, ctrl) {



                }
            }
        });
})();